package com.cn.http;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(10221)) {
            System.out.println("Server is listening on port 10221");

            while (true) {
                try (Socket accept = serverSocket.accept()) {
                    System.out.println("Client connected");

                    // 读取请求头，获取 Content-Length 等信息
                    BufferedReader reader = new BufferedReader(new InputStreamReader(accept.getInputStream(), StandardCharsets.UTF_8));
                    StringBuilder requestBuilder = new StringBuilder();
                    String line;
                    int contentLength = 0;

                    while ((line = reader.readLine()) != null) {
                        requestBuilder.append(line).append("\r\n");
                        // 检查 Content-Length
                        if (line.startsWith("Content-Length:")) {
                            contentLength = Integer.parseInt(line.split(":")[1].trim());
                        }
                    }

                    // 如果有请求体，读取请求体内容
                    StringBuilder requestBody = new StringBuilder();
                    if (contentLength > 0) {
                        char[] body = new char[contentLength];
                        reader.read(body, 0, contentLength);
                        requestBody.append(body);
                    }

                    // 输出完整的请求头和请求体
                    System.out.println("Complete request data: " + requestBuilder.toString());
                    System.out.println("Request body: " + requestBody.toString());

                    // 解析 JSON 数据（可以使用 org.json 或 Gson）
                    // JSONObject json = new JSONObject(requestBody.toString());
                    // String value = json.getString("key"); // 示例：获取某个字段的值

                    // 发送响应
                    try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(accept.getOutputStream(), StandardCharsets.UTF_8)) {
                        outputStreamWriter.write("HTTP/1.1 200 OK\r\n");
                        outputStreamWriter.write("Content-Type: application/json\r\n");
                        outputStreamWriter.write("Connection: close\r\n");
                        outputStreamWriter.write("\r\n");
                        outputStreamWriter.write("{\"status\": \"success\"}");
                        outputStreamWriter.flush();
                    }
                } catch (IOException e) {
                    System.err.println("Error handling client connection: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.err.println("Server error: " + e.getMessage());
        }
    }
}
